package com.cube.share.jackson.factory;

import com.cube.share.jackson.annotation.SearchEscape;
import com.cube.share.jackson.util.EscapeUtil;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.Parser;
import org.springframework.format.Printer;

import java.io.Serializable;
import java.util.Collections;
import java.util.Locale;
import java.util.Set;

/**
 * @author poker.li
 * @date 2021/10/26 16:26
 */
public class SearchEscapeFormatterFactory implements AnnotationFormatterFactory<SearchEscape> {

    private final static Set<Class<?>> FIELD_TYPES;

    public final static SearchEscapeFormatterFactory INSTANCE = new SearchEscapeFormatterFactory();

    static {
        FIELD_TYPES = Collections.singleton(String.class);
    }

    @Override
    public Set<Class<?>> getFieldTypes() {
        return FIELD_TYPES;
    }

    @Override
    public Printer<?> getPrinter(SearchEscape annotation, Class<?> fieldType) {
        return new SearchEscapeFormatter(annotation);
    }

    @Override
    public Parser<?> getParser(SearchEscape annotation, Class<?> fieldType) {
        return new SearchEscapeFormatter(annotation);
    }

    private static class SearchEscapeFormatter implements Formatter<String>, Serializable {


        private static final long serialVersionUID = 2390760059864209094L;

        private final char[] needsToEscape;

        SearchEscapeFormatter(SearchEscape searchEscape) {
            this.needsToEscape = searchEscape.needsToEscape();
        }

        @Override
        public String parse(String text, Locale locale) {
            return EscapeUtil.escape(text, needsToEscape);
        }

        @Override
        public String print(String object, Locale locale) {
            return object;
        }
    }
}
